import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('JWT_SECRET'),
    });
  }

//   async validate(payload: any) {
//     console.log('JwtStrategy validate', payload);
//     return { userId: payload.sub, mobile: payload.mobile };
//   }
  async validate(payload: any) {
    console.log('Payload received:', JSON.stringify(payload.roles, null, 2));
    if (!payload.sub || !payload.mobile) {
      throw new UnauthorizedException('Invalid token payload');
    }
    return { userId: payload.sub, mobile: payload.mobile , roles: payload.roles};
  }
}